﻿using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Reflection;
using System.Windows.Forms;

namespace Natalie.Framework.UI.TypeEditors
{
    public class SaveFileNameEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (context.Instance == null)
            {
                return base.EditValue(context, provider, value);
            }

            FieldInfo autoGeneratedFileNameField = context.Instance.GetType().GetField("autoGeneratedFileName",
                                                              BindingFlags.NonPublic | BindingFlags.Instance);

            var autoGeneratedFileName = string.Empty;

            if (autoGeneratedFileNameField != null)
            {
                var autoGeneratedFileNameFieldValue = autoGeneratedFileNameField.GetValue(context.Instance);

                if (autoGeneratedFileNameFieldValue != null)
                {
                    autoGeneratedFileName = autoGeneratedFileNameFieldValue.ToString();
                }
            }

            using (var saveFileDialog = new SaveFileDialog())
            {
                if (value != null)
                {
                    saveFileDialog.FileName = value.ToString();
                }
                
                saveFileDialog.Title = context.PropertyDescriptor.DisplayName;
                saveFileDialog.DefaultExt = "txt";
                saveFileDialog.Filter = "Text Files|*.txt|All files|*.*";

                if(!string.IsNullOrWhiteSpace(autoGeneratedFileName) && autoGeneratedFileName.Length < 100)
                {
                    saveFileDialog.FileName = autoGeneratedFileName;
                }

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    value = saveFileDialog.FileName;
                }
            }

            return value;
        }
    }

}
